<template>
        <section>
            <el-col :sm="24" :lg="16">
                <div class="grid-content bg-purple" :style="{backgroundColor:titleColor}">
                    <div class="dev-title">编辑设备模板</div>
                </div>
                <div class="col-bg clearfix">
                        <el-form ref="form" :rules="addFormRules" :model="form" label-width="120px" @submit.prevent="onSubmit"
                        style="padding: 15px;margin:20px auto 10px;max-width: 900px;">
                     
                        <el-form-item label="设备模板名称" class="grade" prop="name">
                                <el-input v-model="form.name"></el-input>
                            </el-form-item>
                        <!-- <el-form-item label="终端用户" class="grade" prop="terminalUser">
                              
                                <el-select v-model="form.terminalUser" placeholder="终端用户">
                                        <el-option v-for="item in terminal_list" :label="item.name" :value="item.id"></el-option>
                                    </el-select>
                            </el-form-item> -->
                        <!-- <el-form-item label="设备分组" class="grade" prop="deviceGroupId">
                            <el-select v-model="form.deviceGroupId" placeholder="请选择活动区域">
                                <el-option v-for="item in grouplist" :label="item.name" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item> -->
                        <el-form-item label="设备类型" class="grade" prop="deviceTypeId">
                            <el-select v-model="form.deviceTypeId" placeholder="请选择设备类型">
                                <el-option v-for="item in typelist" :label="item.name" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="网关型号" class="grade" prop="deviceModelId">
                            <el-select v-model="form.deviceModelId" placeholder="请选择网关型号">
                                <el-option v-for="item in modellist" :label="item.name" :value="item.modelId"></el-option>
                            </el-select>
                        </el-form-item>
                        <!-- <el-form-item label="设备所属用户" class="grade" prop="deviceUserId">
                            <el-select v-model="form.deviceUserId" placeholder="请选择所属用户">
                                <el-option v-for="item in userlist" :label="item.name" :value="item.companyId"></el-option>
                            </el-select>
                        </el-form-item> -->
                        <!-- <el-form-item label="通信协议" prop="protocol">
                            <el-radio-group v-model="form.protocol">
                                <el-radio label="0" checked>Modbus TCP</el-radio>
                            </el-radio-group>
                        </el-form-item> -->
    
                        <el-form-item label="移动属性" class="grade" prop="moving">
                            <el-radio-group v-model="form.moving">
                                <el-radio label="0">静止</el-radio>
                                <el-radio label="1">移动</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <!-- <el-form-item label="订单名称" class="grade" prop="orderSn">
                            <el-select v-model="form.orderSn">
                                <el-option v-for="item in orderlist" :label="item.name" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item> -->
                        <el-form-item label="行业" prop="guild" class="grade">
                            <!-- <el-input v-model="form.guild"></el-input> -->
                            <el-select v-model="form.guild" placeholder="请选择行业">
                                <el-option v-for="item in industrylist" :label="item.remark" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                        <!-- <el-form-item label="UI模板">
                            <el-select v-model="form.uiId" placeholder="UI模板">
                                <el-option v-for="item in templateUIlist" :label="item.name" :value="item.uiId"></el-option>
                            </el-select>
                        </el-form-item> -->
                        <!-- <el-form-item label="排序值" prop="area">
                            <el-input type="number" v-model="form.area"></el-input>
                        </el-form-item> -->
                        <!-- <el-form-item label="是否体验设备">
                    <el-radio-group v-model="form.experience">
                        <el-radio label="0">否</el-radio>
                        <el-radio label="1">是</el-radio>
                    </el-radio-group>
                </el-form-item> -->
                        <el-form-item label="备注"  >
                            <el-input type="textarea" v-model="form.remark"></el-input>
                        </el-form-item>
                      
                        <el-form-item label-position="center">
                            <div class="grid-content bg-purple">
                                <div class="dev-title">设备地图</div>
                            </div>
                            <div id="allmap" ref="allmap">
                            </div>
                            <div class="map_position clearfix ng-binding">
                                <el-input type="text" id="suggestId" name="address_detail" placeholder="地址" v-model="address_detail"
                                    class="input_style"></el-input>
                                <!-- <div>{{form.deviceLocation.address}}</div> -->
                                经度：{{form.deviceLocation.longitude}},纬度：{{form.deviceLocation.latitude}}
                            </div>
    
                        </el-form-item>
                        <el-form-item label="设备图片">
                            <!-- <el-form-item label="排序值" class="grade">
                                <el-input v-model="form.devicePictureList[0].priority"></el-input>
                            </el-form-item> -->
                            <el-form-item label="图片">
                                <el-upload class="avatar-uploader" :headers="fileList" action="/api/auth/image_file/upload"
                                    :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                </el-upload>
                            </el-form-item>
                        </el-form-item>
                        <el-form-item label="设备从机">
    
                            <el-row :gutter="10" style="padding:0 10px" v-for="(item,index) in  form.deviceSlaveList">
                                <!-- <el-col :span="5">
                                    <el-input v-model="item.priority" auto-complete="off" placeholder="排序值"></el-input>
                                </el-col> -->
                                <el-col :span="5">
                                    <el-input v-model="item.name" auto-complete="off" placeholder="从机名称"></el-input>
                                </el-col>
                                <el-col :span="5">
                                    <el-input type='number' v-model="item.slaveSn" auto-complete="off" placeholder="从机编号"></el-input>
                                </el-col>
                                <el-col :span="5">
                                    <el-select v-model="item.deviceDataRecipeId" placeholder="请选择数据模板">
                                        <el-option v-for="list in recipelist" :label="list.name" :value="list.id"></el-option>
                                    </el-select>
                                </el-col>
                                <el-col :span="4">
                                    <i class="el-icon-delete" @click="deviceSlaveListdel(index)" style="color:red;font-size:20px;line-height:40px;"></i>
                                </el-col>
                            </el-row>
                            <el-button style="position:absolute;right:10%;bottom: 0" @click.native.prevent="deviceSlaveListadd()" :type="buttonColor">添加设备从机</el-button>
                        </el-form-item>
    
                        <el-form-item>
                            <!-- <el-button @click.native.prevent="deviceSlaveListadd()" :type="buttonColor">添加设备从机</el-button> -->
                            <el-button  @click.native.prevent="onSubmit()" :type="buttonColor" :loading="addLoading">保存</el-button>
                            <!-- <el-button @click.native.prevent>取消</el-button> -->
                        </el-form-item>
                    </el-form>
                </div>
            </el-col>
        </section>
    
    </template>
    
    <script>
        import {
            file_upload,
            device_template_put,
            device_group_query,
            device_type_query,
            device_model_query,
            user_query,
            device_template_get,
            device_data_recipe_query,
            dict_query,
            terminal_user_query,
            order_query,
            query_device_user,
            template_ui_query,
            device_template_ui_company_query
        } from '../../api/api';
        export default {
            data() {
                return {
                    addFormRules: {
                        orderSn: [{
                            required: true,
                            message: '必填',
                            trigger: 'blur'
                        }],
                        deviceSn: [{
                            required: true,
                            message: '网关SN必填',
                            trigger: 'blur'
                        }],
                        name: [{
                            required: true,
                            message: '设备模板名称必填',
                            trigger: 'blur'
                        },{ min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }],
                        password: [{
                            required: true,
                            message: '设备密码必填',
                            trigger: 'blur'
                        }],
                        deviceGroupId: [{
                            required: true,
                            message: '设备分组必填',
                            trigger: 'blur'
                        }],
                        deviceTypeId: [{
                            required: true,
                            message: '设备类型必填',
                            trigger: 'blur'
                        }],
                        deviceModelId: [{
                            required: true,
                            message: '网关型号必填',
                            trigger: 'blur'
                        }],
                        deviceUserId: [{
                            required: true,
                            message: '设备所属用户必填',
                            trigger: 'blur'
                        }],
                        protocol: [{
                            required: true,
                            message: '通信协议',
                            trigger: 'blur'
                        }],
                        moving: [{
                            required: true,
                            message: '必填',
                            trigger: 'blur'
                        }],
                        guild: [{
                            required: true,
                            message: '必填',
                            trigger: 'blur'
                        }],
                       // area: [{
                       //     required: true,
                       //     message: '必填',
                      //      trigger: 'blur'
                      //  }],
                        priority: [{
                            required: true,
                            message: '必填',
                            trigger: 'blur'
                        }],
                        experience: [{
                            required: true,
                            message: '必填',
                            trigger: 'blur'
                        }],
                        remark: [{
                            required: true,
                            message: '必填',
                            trigger: 'blur'
                        }],
                        terminalUser: [{
                            required: true,
                            message: '必填',
                            trigger: 'blur'
                        }],
    
                    },
                    terminal_list:'',
                    industrylist:'',
                    userlocation: {
                        lng: "",
                        lat: ""
                    },
                    address_detail: null,
                    recipelist: '',
                    grouplist:[],
                    typelist: '',
                    modellist: '',
                    userlist: '',
                    addLoading: false,
              
                    orderlist:'',
                    priority: '',
                    imageUrl: '',
                    form: {
                      
                        name: '',
                        deviceGroupId: '',
                        deviceTypeId: '',
                        deviceModelId: '',
                        deviceUserId: '',
                        protocol: '',
                        moving: '',
                        guild: '',
                        area: '',
                        orderSn:'',
                        priority: '',
                        experience: '',
                        remark: '',
                        terminalUser: '',
                        uiId: '',
                        deviceLocation: {
                            longitude: '',
                            latitude: '',
                            province: '',
                            city: '',
                            county: '',
                            address: ''
                        },
                        devicePictureList: [{
                            priority: '',
                            path: '',
                        }],
                        deviceSlaveList: [{
                            priority: '',
                            name: '',
                            slaveSn: '',
                            deviceDataRecipeId: ''
                        }],
    
    
                    },
                    fileList: {
                        token: JSON.parse(localStorage.getItem('key'))
                    },
                    templateUIlist:[]
                }
            },
            computed:{
                buttonColor(){
                    return this.$store.state.buttonColor
                },
                titleColor(){
                    return this.$store.state.titleColor
                },
                dialogTitleColor(){
                    return this.$store.state.dialogTitleColor
                },
            },
            methods: {
                map() {
                    var th=this;
                    let self = this;
                    let map = new BMap.Map(this.$refs.allmap);;
                    // 创建Map实例
                    // map.centerAndZoom(new BMap.Point(116.404, 39.915), 5);
                    var poi = new BMap.Point(this.form.deviceLocation.longitude, this.form.deviceLocation.latitude);
                    map.addControl(new BMap.NavigationControl());
                    map.enableScrollWheelZoom(poi, 5);
                    let pt1 = new BMap.Point(
                        this.form.deviceLocation.longitude,
                        this.form.deviceLocation.latitude
                    );
                    let marker1 = new BMap.Marker(pt1);
                    map.addOverlay(marker1);
                    map.centerAndZoom(poi, 15);
                        var ac = new BMap.Autocomplete( //建立一个自动完成的对象
                        {
                            "input": "suggestId",
                            "location": map
                        })
                    var myValue
                    ac.addEventListener("onconfirm", function (e) { //鼠标点击下拉列表后的事件
                        var _value = e.item.value;
                        myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
                        th.address_detail = myValue;
                        self.form.deviceLocation.address = myValue;
                        setPlace();
                    });
    
                    function setPlace() {
                        map.clearOverlays(); //清除地图上所有覆盖物
                        function myFun() {
                            th.userlocation = local.getResults().getPoi(0).point; //获取第一个智能搜索的结果
                            map.centerAndZoom(th.userlocation, 18);
                            map.addOverlay(new BMap.Marker(th.userlocation)); //添加标注
                            
                        self.form.deviceLocation.longitude = th.userlocation.lng;
                        self.form.deviceLocation.latitude = th.userlocation.lat;
                        console.log(th.userlocation)
                        }
                        var local = new BMap.LocalSearch(map, { //智能搜索
                            onSearchComplete: myFun
                        });
                        local.search(myValue);
    
                        //测试输出坐标（指的是输入框最后确定地点的经纬度）
                        map.addEventListener("click", function (e) {
                            //经度
                            console.log(th.userlocation.lng);
                            //维度
                            console.log(th.userlocation.lat);
    
                        })
                    }
                    // map.addEventListener("mousemove", function (e) {
                    //     console.log(e.point)
                    // });
                    map.addEventListener("click", function (e) {
                        map.clearOverlays()
                        //    alert(JSON.stringify(e.point))
                        let pt = new BMap.Point(
                            e.point.lng,
                            e.point.lat
                        );
                        self.form.deviceLocation.longitude = e.point.lng;
                        self.form.deviceLocation.latitude = e.point.lat;
                        let marker = new BMap.Marker(pt);
                        map.addOverlay(marker);
                        var geoc = new BMap.Geocoder();
                        let addComp, address;
                        geoc.getLocation(e.point, function (rs) {
                            addComp = rs.addressComponents;
    
                            self.form.deviceLocation.province = addComp.province;
                            self.form.deviceLocation.city = addComp.city;
                            self.form.deviceLocation.county = addComp.district;
                            address = addComp.province + addComp.city + addComp.district + addComp.street +
                                addComp.streetNumber;
    
                            self.form.deviceLocation.address = address;
    
                        });
    
    
    
                    });
                },
                deviceSlaveListdel(s) {
                    if (this.form.deviceSlaveList.length <= 1) {
                    this.$message({
                        message: '从机最少为一个',
                        type: 'warning'
                    });
                    return false
                }
                    this.form.deviceSlaveList.splice(s, 1)
                },
                deviceSlaveListadd() {
                    this.form.deviceSlaveList.push({
                        priority: '',
                        name: '',
                        slaveSn: '',
                        deviceDataRecipeId: ''
                    })
                },
                getlist() {
                    let para = {
                        pageNo: 1,
                        pageSize: 1000,
                        type:0,
                    authType: 0
    
                    }
                    device_group_query(para).then((res) => {
                         this.begCode(res.code,res.message);
                        let _this=this;
                        this.addLoading = false;
                        if (res.code == 0) {
                            foo(res.data)
                            function foo(n) {
                                for (let i in n) {
                                    if (!n[i]) {
                                        console.log(i)
                                        return true;
                                    }
                                    _this.grouplist.push(n[i]);
                                    console.log(n[i].name)
                                    foo(n[i].childrens)
                                }
                                // return foo(n.childrens);
                            }
                        } else {
                            this.$message({
                                message: res.message,
                                type: 'warning'
                            });
                        }
    
                    });
                    device_data_recipe_query(para).then((res) => {
                         this.begCode(res.code,res.message);
    
                        this.addLoading = false;
                        if (res.code == 0) {
                            this.recipelist = res.data.list;
                        } else {
                            this.$message({
                                message: res.message,
                                type: 'warning'
                            });
                        }
    
                    });
    
                    device_type_query(para).then((res) => {
                         this.begCode(res.code,res.message);
    
                        this.addLoading = false;
                        if (res.code == 0) {
                            this.typelist = res.data.list;
                        } else {
                            this.$message({
                                message: res.message,
                                type: 'warning'
                            });
                        }
    
                    });
                    device_model_query(para).then((res) => {
                         this.begCode(res.code,res.message);
    
                        this.addLoading = false;
                        if (res.code == 0) {
                            this.modellist = res.data.list;
                        } else {
                            this.$message({
                                message: res.message,
                                type: 'warning'
                            });
                        }
    
                    });
                    query_device_user(para).then((res) => {
                         this.begCode(res.code,res.message);
    
                        this.addLoading = false;
                        if (res.code == 0) {
                            this.userlist = res.data.list;
                        } else {
                            this.$message({
                                message: res.message,
                                type: 'warning'
                            });
                        }
    
                    });
                },
                onSubmit() {
                    this.$refs.form.validate((valid) => {
                    if (valid) {
                    this.$confirm('确认提交吗？', '提示', {}).then(() => {
                      //  this.addLoading = true;
                        //NProgress.start();
                        if (this.form.devicePictureList[0]) {
    
                            this.form.devicePictureList[0].priority = this.priority;
                            this.form.devicePictureList[0].path = this.imageUrl;
    
                        } else {
                            let num = {
                                priority: this.priority,
                                path: this.imageUrl
                            }
                            this.form.devicePictureList.push(num)
                        }
                        
                        for(let i in this.form.deviceSlaveList){//从机编号如果为0开头就把0删掉，单独一个0除外
                           // console.log(this.form.deviceSlaveList[i].slaveSn.length)
                            if(this.form.deviceSlaveList[i].slaveSn.indexOf(0)===0 && this.form.deviceSlaveList[i].slaveSn.length>1){
                              let str = this.form.deviceSlaveList[i].slaveSn
                              let change = str.split("")
                                  change = str.replace(0,"")
                                this.form.deviceSlaveList[i].slaveSn = change   
                            }
                        }
                        let para = Object.assign({}, this.form);
                        for (let i in this.form.deviceSlaveList) {
                        if (
                            !this.form.deviceSlaveList[i].slaveSn ||
                            !this.form.deviceSlaveList[i].name ||
                            !this.form.deviceSlaveList[i].deviceDataRecipeId
                        ) {
                            this.addLoading = false;
                            this.$message({
                            message: "从机名称和从机编号数据模板必填",
                            type: "warning"
                            });
                            return false;
                        }
                        }
                        let filterSlave = {}
                        const data2 = this.form.deviceSlaveList.reduce((preVal, curVal) => {
                            filterSlave[curVal.name] ? '' : filterSlave[curVal.name] = true && preVal.push(curVal); 
                            return preVal 
                        }, [])
                        //console.log(data2)
                        //console.log(this.form.deviceSlaveList)
                        //先去重，然后判断是否和原数组数量相同，不相同就存在重复
                        if(data2.length != this.form.deviceSlaveList.length){
                            this.$message({
                                message: "从机名称重复",
                                type: "warning"
                            });
                            return false;
                        }
    
                        device_template_put(para).then((res) => {
                             this.begCode(res.code,res.message);
    
                            this.addLoading = false;
                            if (res.code == 0) {
    
                                //NProgress.done();
                                this.$message({
                                    message: '修改成功',
                                    type: 'success'
                                });
                                this.$router.push({
                                    path: "/template/device"
                                });
                           } else {
                                this.$message({
                                   message: res.message,
                                    type: 'warning'
                                });
                          }
    
                       });
                    });
                    }else{
                        this.$message({
                                        message: '请把信息填写完整',
                                        type: 'warning'
                                    });
                    }
                    });
                },
                handleAvatarSuccess(res, file) {
                    console.log(file)
                    console.log(res.data.path)
                    this.imageUrl = res.data.path;
                    // this.form.devicePictureList[0].path = res.data.path;
                },
                beforeAvatarUpload(file) {
                    const isJPG = file.type === 'image/jpeg';
                    const isPNG = file.type === 'image/png';
                    const isGIF = file.type === 'image/gif';
                    let tp = false;
                    if (isJPG) {
                        tp = isJPG;
                    } else if (isPNG) {
                        tp = isPNG
                    } else if (isGIF) {
                        tp = isGIF
                    } else {
    
                    }
                    const isLt2M = file.size / 1024 / 1024 < 1;
                    if (!isJPG && !isPNG && !isGIF) {
                        this.$message.error('上传头像图片只能是 JPG,GIF,PNG 格式!');
                    }
                    if (!isLt2M) {
                        this.$message.error('上传头像图片大小不能超过 1MB!');
                    }
                    return tp && isLt2M;
                },
            },
            mounted() {
                this.getlist();
                let deviceId = sessionStorage.getItem('deviceId');
                let para = {
                    id: deviceId
    
                }
                device_template_get(para).then((res) => {
                     this.begCode(res.code,res.message);
    
                    this.addLoading = false;
                    if (res.code == 0) {
                        this.form = res.data;
                        console.log(this.form.deviceSn)
                        if (res.data.devicePictureList[0]) {
                            this.priority = res.data.devicePictureList[0].priority;
                            this.imageUrl = res.data.devicePictureList[0].path;
    
                        } else {
    
                        }
                        this.form.moving = res.data.moving.toString();
                        this.form.priority = res.data.priority.toString();
                        if (this.form.protocol) {
    
                            this.form.protocol = this.form.protocol.toString();
    
                        }
                        this.map();
                        // this.form.moving=res.data.moving.tostring();
                    } else {
                        this.$message({
                            message: res.message,
                            type: 'warning'
                        });
                    }
    
                });
                let para2 = {
                            pageNo: 1,
                            pageSize: 9999,
                        };
                        this.listLoading = true;
                        //NProgress.start();
                        terminal_user_query(para2).then((res) => { this.begCode (res.code);
                            this.total = res.data.totalCount;
                            this.terminal_list = res.data.list;
                            this.listLoading = false;
                            //NProgress.done();
                        });
                let para1 = {
                    name: 'industry',
                    pageSize: 999,
                    pageNo: 1,
                }
                dict_query(para1).then((res) => { this.begCode (res.code);
                    if (res.code == 0) {
                        this.addLoading = false;
    
                        this.industrylist = res.data.list;
    
    
                    }
    
                });
            
                order_query(para2).then((res) => {
                     this.begCode(res.code,res.message);
                    if (res.code == 0) {
    
                        this.orderlist = res.data.list;
    
    
                    }
    
                });
               // template_ui_query().then(res => {
                device_template_ui_company_query().then(res => {
                    if(res.code == 0){
                        this.templateUIlist = res.data.list;
                    }
                })
            }
            
        }
    </script>
    <style>
        .el-form-item .el-form-item {
            margin-bottom: 22px;
        }
    
        .avatar-uploader .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }
    
        .avatar-uploader .el-upload:hover {
            border-color: #409EFF;
        }
    
        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            line-height: 178px;
            text-align: center;
        }
    
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }
    
        #allmap {
            height: 400px;
        }
    </style>